import xml.etree.ElementTree as ET
from xml.etree.ElementTree import ElementTree,Element
import os

def indent(elem, level=0, returnChar='\n', indentChar='\t'):
    i = returnChar + level * indentChar
    if len(elem):
        if not elem.text or not elem.text.strip():
            elem.text = i + indentChar
        for e in elem:
            indent(e, level + 1)
        if not e.tail or not e.tail.strip():
            e.tail = i
    if level and (not elem.tail or not elem.tail.strip()):
        elem.tail = i
    return elem

def read_xml(in_path):
    tree = ElementTree()
    tree.parse(in_path)
    return tree
  
def write_xml(tree, out_path, statment):
    tree.write(out_path, encoding="utf-8",xml_declaration=statment)
  
def if_match(node, kv_map):
    for key in kv_map:
        if key not in node.attrib:
            return False
        if node.get(key) != kv_map.get(key):
            return False
    return True

#---------------search -----
  
def find_nodes(tree, path):
    return tree.findall(path)
  
  
def get_node_by_keyvalue(nodelist, kv_map):
    result_nodes = []
    for node in nodelist:
        if if_match(node, kv_map):
            result_nodes.append(node)
    return result_nodes
  
#---------------change -----

def change_node_properties(nodelist, kv_map, is_delete = False):  
    for node in nodelist:
        for key in kv_map:
            if is_delete:
                if key in node.attrib:
                    del node.attrib[key]
            else:
                node.set(key, kv_map.get(key))
              
def change_node_text(nodelist, text, is_add = False, is_delete=False):  
    for node in nodelist:  
        if is_add:  
            node.text += text  
        elif is_delete:  
            node.text = ""  
        else:  
            node.text = text  
              
def create_node(tag, property_map, content):  
    element = Element(tag, property_map)  
    element.text = content  
    return element  
          
def add_child_node(nodelist, element):  
    for node in nodelist:  
        node.append(element)  
          
def del_node_by_tagkeyvalue(nodelist, tag, kv_map):  
    for parent_node in nodelist:  
        children = parent_node.getchildren()  
        for child in children:
            if child.tag  == tag  and if_match(child, kv_map):  
                parent_node.remove(child)

def readFromString(content):
    return ET.fromstring(content)

def _writeXML(root, path):
    try:
        tree = ElementTree(root)
        tree.write(path, xml_declaration = 'True', encoding='utf-8')
    except:
        pass

def writeXML(root, dirPath, fileName):
    if not os.path.exists(dirPath):
        os.makedirs(dirPath)
    outName = dirPath + os.sep + fileName
    _writeXML(root, outName)

